<template>
      <h1>支付页面</h1>
      <el-main>
      <el-scrollbar>
        <el-tag type="success">检查项目金额合计为：{{checkPrice}}</el-tag>
 
        <el-table  ref="multipleTableRef"
    :data="tableData"
    style="width: 100%"
  
    size="mini"  >
    <el-table-column   width="150" />
    <el-table-column property="techName" label="项目名称" width="200" />
    <el-table-column property="techPrice" label="单价" width="200" />
    <el-table-column property="count" label="数量" width="200" />
    <el-table-column property="createTime" label="开立时间" width="200" />
  </el-table>
      </el-scrollbar>
    </el-main>
  <el-form
    style="max-width: 600px"
    :model="sizeForm"
    label-width="auto"
    :label-position="labelPosition"
    :size="size"
  >
    <el-form-item label="病人id" prop="registerId">
      <el-input v-model="sizeForm.registerId" placeholder="输入病人id" disabled/>
    </el-form-item>
    <el-form-item label="费用类型名称" prop="typeId">
      <el-input  v-model="sizeForm.type" placeholder="输入费用类型" disabled/>
    </el-form-item>
    <el-form-item label="费用类型" prop="typeId">
      <el-input  v-model="sizeForm.typeId" placeholder="输入费用类型" disabled/>
    </el-form-item>
    <el-form-item v-on="getOrderNo()" label="订单编号" prop="outTradeNo">
      <el-input v-model="sizeForm.outTradeNo" placeholder="输入订单编号" disabled />
    </el-form-item>
    <el-form-item label="病人姓名" prop="realName">
      <el-input v-model="sizeForm.realName" placeholder="输入病人姓名"  disabled/>
    </el-form-item>
    <el-form-item label="应付金额" prop="techPrice">
      <el-input v-model="sizeForm.techPrice" placeholder="输入应付金额" disabled/>
    </el-form-item>
    <el-form-item label="实付金额" prop="totalAmount">
      <el-input v-model="sizeForm.totalAmount" placeholder="输入实付金额" />
    </el-form-item>
    <el-form-item label="概要标题" prop="subject">
      <el-input v-model="sizeForm.subject" placeholder="输入项目名称" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit" style="width: 100px;" plain>提交订单</el-button>
      <el-button @click="pay" round type="primary">立即支付</el-button>
      <el-button @click="onCancel" type="warning" style="width: 100px;">取消支付</el-button>
      <el-button @click="resetForm" style="width: 100px;" type="danger">重置表单</el-button>
      <el-button @click="downloadPayInfo">下载支付凭证</el-button>
    </el-form-item>
  </el-form>
  <div>
        <!-- 其他内容 -->
        <form id="payment-form" action="http://localhost:6666/alipay/pay"  method="POST" style="display:none;">
            <input type="hidden" name="out_trade_no" v-model="sizeForm.outTradeNo" />
            <input type="hidden" name="total_amount" v-model="sizeForm.totalAmount" />
            <input type="hidden" name="subject" v-model="sizeForm.subject" />
        </form>
        <button @click="pay">支付</button>
    </div>
   
  </template>
  
  <script lang="ts" setup name="PayMoney">
import { reactive, ref } from 'vue';
import router from '@/router';
import { ComponentSize, FormProps } from 'element-plus'
import axiosInstance from '@/utils/axiosUtils';
import { useRoute } from 'vue-router';
const route=useRoute();
const size = ref<ComponentSize>('default')
const labelPosition = ref<FormProps['labelPosition']>('right')
const requestsPrice=route.query.requestsPrice;
const selectedRequests=route.query.selectedRequests;

const realName=route.query.realName;
const registerId=route.query.registerId;
const type=route.query.type;
console.log(type);
console.log(realName);
interface patientRequest{
 id:number,
 techName: string,
 techPrice:number,
 priceType: string,
 createTime:Date,//后端转换为LocalDateTime
 count:number
}
const patientRequests=ref<patientRequest[]>([]);
  if (Array.isArray(selectedRequests)) {
    // 如果是数组，则使用 JSON.stringify 转换为字符串
    patientRequests.value = JSON.parse(JSON.stringify(selectedRequests));
} else {
    // 如果是字符串，则直接解析
    patientRequests.value = JSON.parse(selectedRequests);
}

//数据表引用类型
interface User {
   id:number,
   techName: string,
   deptId:number,
   techPrice:number,
   priceType: string,
   techType: string,
}
//检查数据初始值
const tableData=ref( [
  {
     id:null,
     techName: null,
     techPrice: null,
     priceType:null,
     techType: null,
     createTime:null,
     count:null
  }
])
 
//获取字符串化的数组，先字符串化对象，再转化为数组，最后转化为对象
const checkPrice =   requestsPrice;
const checksArr=JSON.stringify(selectedRequests);//先将字符串转化为数组
const checksList=JSON.parse(checksArr);//再将数组转化为对象
tableData.value=JSON.parse(checksList);//将对象转化为数组
let typeId=ref(0);
if(type=='register'){
  typeId.value=1;
}
if(type=='check'){
  typeId.value=2;
}
if(type=='inspection'){
  typeId.value=3;
}
if(type=='disposal'){
  typeId.value=4;
}
if(type=='prescription'){
  typeId.value=5;
} 

 const getOrderNo=()=>{
  axiosInstance.get('/api/payOrder/getOrderNo').then(response=>{
    console.log('outTradeNo:',response.data);
     sizeForm.outTradeNo=JSON.parse(response.data);
  }).catch(error=>{
    console.log(error);
  });
}

const sizeForm = reactive({
  id: null,
  registerId: registerId, // 防止未定义
  typeId: typeId.value,
  outTradeNo: null, // 确保有默认值
  type: type,
  registerName: null,
  orderNo: null, // 确保有默认值
  realName:realName, // 确保安全调用
  techPrice: checkPrice,
  totalAmount:   requestsPrice,
  subject: null,
  count: 1,
  status: null
});

const payForm = ref({
  id:sizeForm.id,
  regiserId:registerId,
  typeId:sizeForm.typeId,
  outTradeNo:sizeForm.outTradeNo,
  type:sizeForm.type,
  registerName:sizeForm.registerName,
  orderNumber:sizeForm.orderNo,
  realName:sizeForm.realName,
  techPrice:sizeForm.techPrice,
  totalAmount:sizeForm.totalAmount,
  subject:sizeForm.subject,
  count:sizeForm.count
});

const resetForm = () => {
  sizeForm.id=null;
  sizeForm.registerId=null;
  sizeForm.typeId=null;
  sizeForm.outTradeNo=null;
  sizeForm.type=null;
  sizeForm.registerName=null;
  sizeForm.orderNo=null;
  sizeForm.realName=null;
  sizeForm.techPrice=null;
  sizeForm.totalAmount=null;
  sizeForm.subject=null;
  sizeForm.count=1;
  sizeForm.status=null;
};

const onCancel = () => {
 router.push({name:'pay'})
};
//检查项目付费
const payChecks = () => {
 router.push({name:'payMoney',query:{type:'check'}})
}
// const outTradeNo = ref(''); // 订单号 
// const totalAmount = ref(''); // 订单金额
// const subject = ref(''); // 商品名称
const pay = async () => {
    try {
        const response = await axiosInstance.post('/api/alipay/pay', {
            out_trade_no: sizeForm.outTradeNo,
            total_amount: sizeForm.totalAmount,
            subject: sizeForm.subject,
        }, {
            headers: { 'Content-Type': 'application/json' }
        });

        if (response.data.form) {
            // 直接将表单插入到页面中
            const formContainer = document.createElement('div');
            formContainer.innerHTML = response.data.form;

            // 将表单添加到文档中
            document.body.appendChild(formContainer);

            // 提交表单
            formContainer.querySelector('form').submit();
        } else {
            console.error('支付表单数据为空');
        }
    } catch (error) {
        console.error('请求错误:', error);
    }
};

function onSubmit() {
  if(type=='check'){
    axiosInstance.get('/api/payOrder/payChecks',{
      params: {payForm}
    }).then(response=>{
      console.log(response.data);
    }).catch(error=>{
      console.log(error);
    });
  }
  if(type=='check'){
    axiosInstance.post('/api/payOrder/payInspections',{
      params: {payForm}
    }).then(response=>{
      console.log(response.data);
    }).catch(error=>{
      console.log(error);
    });
  }
  if(type=='dispose'){
    axiosInstance.post('/api/payOrder/payDisposals',{
      params: {payForm}
    }).then(response=>{
      console.log(response.data);
    }).catch(error=>{
      console.log(error);
    });
  }
}
console.log(selectedRequests);
const downloadPayInfo = () => {
  if (type == 'check') {
    typeId.value = 2;
  }

 const invoiceDTO = {
    id: null,  // 保留为 null，后端可以处理
    registerId: Number.parseInt(typeof registerId === 'string' ? registerId : registerId[0]), // 保留为数字
    typeId: Number.parseInt(typeId.value.toString()), // 保留为数字
    outTradeNo: sizeForm.outTradeNo, // 保留为字符串
    type: type, // 保留为字符串
    registerName: realName, // 保留为字符串
    patientRequests: patientRequests.value, // 直接保留对象数组
    orderNo: sizeForm.orderNo, // 保留为字符串
    techPrice: Number.parseFloat(sizeForm.techPrice.toString()), // 保留为数字
    totalAmount: Number.parseFloat(requestsPrice.toString()), // 保留为数字
    subject: sizeForm.subject, // 保留为字符串
    status: "订单已创建" // 字符串
};

// 将对象转换为 JSON 字符串
const invoiceJSONString = JSON.stringify(invoiceDTO);

// 输出 JSON 字符串
console.log(invoiceJSONString);

  console.log(invoiceDTO);

  axiosInstance.post('/api/file/downloadRequestPayInfo', 
    {
      invoiceDTO:invoiceJSONString, // 直接传递对象
    },
    {
      headers: {
        'Content-Type': 'application/json'
      }
    }
  ).then(response => {
 

    console.log(invoiceDTO);
  }).catch(error => {
    console.log(error);
  });
};

  </script>
  